import axios from 'axios'
import config from './config'

export default class ajax {
    constructor() {
        let http = axios.create({
            baseURL: config()
        })

        http.interceptors.request.use(config => {
            // if (config.method == 'post') {
            //     // 数据序列化成表单
            //     const formData = new FormData()
            //     Object.keys(config.data).forEach((key) => formData.append(key, config.data[key]))
            //     config.data = formData
            // }
            // config.headers = {
            //     'Content-type': 'application/x-www-from-urlencoded'
            // }
            config.headers['tokenId'] = localStorage.getItem('token')?localStorage.getItem('token'):'';
            return config
        }, error => {
            return Promise.reject(error)
        })

        http.interceptors.response.use(response => {
            const {
                data
            } = response
            if (data && data != "") {
                return data
            } else {
                return ""
            }
        }, error => {
            return Promise.reject(error)
        })

        this._http = http
    }
    get(api, params = {}) {
        return this._http.get(api, {
            params: params
        })
    }

    post(api, params = {}, config) {
        if (config) return this._http.post(api, params, config);
        else {
          // config = {
          //   headers: {
          //     "Content-type": "application/x-www-from-urlencoded"
          //   }
          // };
          // const formData = new FormData();
          // Object.keys(params).forEach(key => formData.append(key, params[key]));
          return this._http.post(api, params);
        }
    }

}